package com.example.rain.threadtest;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {
    private MyService.Myblind myblind;
    private boolean isPause = false;
    private Handler handler;
    private Intent intent;
    private SeekBar seekBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekBar = (SeekBar) findViewById(R.id.se);
        intent = new Intent("myService");
        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                myblind = (MyService.Myblind) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        }, BIND_AUTO_CREATE);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
               int s= msg.getData().getInt("pro");
                seekBar.setProgress(s);
            }
        };

    }
    public void play(View view) {
        if (isPause) {
            isPause = false;
            synchronized (handler) {
                handler.notify();
            }
        }
        else {
            start();
        }

    }
    public void start() {
        startService(intent);
        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    synchronized (handler) {
                        if (isPause) {
                            try {
                                handler.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Message message = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putInt("pro", myblind.getProgress());
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }
        }.start();


    }

    public void pause(View view) {
        isPause=true;

    }

}